package com.tc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tc.domain.Hospital_reimbursement_ratio;
import com.tc.domain.Insured_person;
import com.tc.domain.Reimbursement_record;
import com.tc.dto.Reimbursement_recordDTO;
import com.tc.dto.Reimbursement_recordQueryDTO;
import com.tc.mapper.Reimbursement_recordMapper;
import com.tc.service.IHospital_reimbursement_ratioService;
import com.tc.service.IInsured_personService;
import com.tc.service.IReimbursement_recordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tc.vo.PageResultVO;
import com.tc.vo.Reimbursement_recordVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  报销记录服务实现类
 * </p>
 *
 * @author jcd
 * @since 2025-07-09
 */
@Service
public class Reimbursement_recordServiceImpl extends ServiceImpl<Reimbursement_recordMapper, Reimbursement_record> implements IReimbursement_recordService {

    @Autowired
    private IInsured_personService insuredPersonService;
    
    @Autowired
    private IHospital_reimbursement_ratioService hospitalReimbursementRatioService;

    @Override
    public PageResultVO<Reimbursement_recordVO> pageQuery(Reimbursement_recordQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<Reimbursement_record> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (queryDTO.getPatientId() != null) {
            queryWrapper.eq(Reimbursement_record::getPatientId, queryDTO.getPatientId());
        }
        
        if (StringUtils.hasText(queryDTO.getSettlementType())) {
            queryWrapper.eq(Reimbursement_record::getSettlementType, queryDTO.getSettlementType());
        }
        
        if (queryDTO.getBeginTime() != null) {
            queryWrapper.ge(Reimbursement_record::getReimbursementTime, queryDTO.getBeginTime());
        }
        
        if (queryDTO.getEndTime() != null) {
            queryWrapper.le(Reimbursement_record::getReimbursementTime, queryDTO.getEndTime());
        }
        
        if (queryDTO.getMinAmount() != null) {
            queryWrapper.ge(Reimbursement_record::getReimbursementAmount, queryDTO.getMinAmount());
        }
        
        if (queryDTO.getMaxAmount() != null) {
            queryWrapper.le(Reimbursement_record::getReimbursementAmount, queryDTO.getMaxAmount());
        }
        
        // 按报销时间降序排序
        queryWrapper.orderByDesc(Reimbursement_record::getReimbursementTime);
        
        // 执行分页查询
        Page<Reimbursement_record> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<Reimbursement_record> resultPage = this.page(page, queryWrapper);
        
        // 将实体对象转换为视图对象，并设置患者姓名
        List<Reimbursement_recordVO> records = resultPage.getRecords().stream()
                .map(record -> {
                    Reimbursement_recordVO vo = Reimbursement_recordVO.fromEntity(record);
                    
                    // 查询患者信息
                    if (record.getPatientId() != null) {
                        Insured_person patient = insuredPersonService.getById(record.getPatientId());
                        if (patient != null) {
                            vo.setPatientName(patient.getName());
                        }
                    }
                    
                    return vo;
                })
                .collect(Collectors.toList());
        
        // 使用PageResultVO的静态方法直接构建分页结果对象
        return PageResultVO.convert(resultPage, records);
    }

    @Override
    public Reimbursement_recordVO getReimbursementRecordById(Long id) {
        Reimbursement_record record = this.getById(id);
        if (record == null) {
            return null;
        }
        
        Reimbursement_recordVO vo = Reimbursement_recordVO.fromEntity(record);
        
        // 查询患者信息
        if (record.getPatientId() != null) {
            Insured_person patient = insuredPersonService.getById(record.getPatientId());
            if (patient != null) {
                vo.setPatientName(patient.getName());
            }
        }
        
        return vo;
    }

    @Override
    @Transactional
    public boolean addReimbursementRecord(Reimbursement_recordDTO recordDTO) {
        Reimbursement_record record = new Reimbursement_record();
        BeanUtils.copyProperties(recordDTO, record);


        // 如果未指定报销金额，则自动计算
        if (record.getReimbursementAmount() == null && record.getTotalCost() != null) {
            Reimbursement_recordVO vo = calculateReimbursementAmount(record.getPatientId(), record.getTotalCost());
            record.setReimbursementAmount(vo.getReimbursementAmount());
            record.setDeductible(vo.getDeductible());
            record.setCeiling(vo.getCeiling());
        }
        
        // 设置默认值
        if (record.getReimbursementTime() == null) {
            record.setReimbursementTime(LocalDateTime.now());
        }
        
        record.setDeleted(0); // 设置为未删除
        
        return this.save(record);
    }

    @Override
    @Transactional
    public boolean updateReimbursementRecord(Reimbursement_recordDTO recordDTO) {
        if (recordDTO.getRecordId() == null) {
            throw new IllegalArgumentException("报销记录ID不能为空");
        }
        
        Reimbursement_record record = new Reimbursement_record();
        BeanUtils.copyProperties(recordDTO, record);
        
        // 如果未指定报销金额，则自动计算
        // 如果未指定报销金额，则自动计算
        if (record.getReimbursementAmount() == null && record.getTotalCost() != null) {
            Reimbursement_recordVO vo = calculateReimbursementAmount(record.getPatientId(), record.getTotalCost());
            record.setReimbursementAmount(vo.getReimbursementAmount());
            record.setDeductible(vo.getDeductible());
            record.setCeiling(vo.getCeiling());
        }
        
        return this.updateById(record);
    }

    @Override
    @Transactional
    public boolean deleteReimbursementRecord(Long id) {
        return this.removeById(id);
    }

    @Override
    public Reimbursement_recordVO calculateReimbursementAmount(Long patientId, BigDecimal totalCost) {
        Reimbursement_recordVO vo = new Reimbursement_recordVO();
        vo.setPatientId(patientId);
        vo.setTotalCost(totalCost);
        vo.setReimbursementAmount(BigDecimal.ZERO);

        if (patientId == null || totalCost == null) {
            return vo;
        }

        // 查询患者信息
        Insured_person patient = insuredPersonService.getById(patientId);
        if (patient == null || !StringUtils.hasText(patient.getPaymentType())
                || "自费".equals(patient.getPaymentType())) {

            return vo;
        }

        // 获取医院等级和人员类型
        String hospitalLevel = patient.getHospitalLevel();
        String personType = patient.getPersonCategory();

        if (!StringUtils.hasText(hospitalLevel) || !StringUtils.hasText(personType)) {
            return vo;
        }

        // 查询适用的报销比例
        LambdaQueryWrapper<Hospital_reimbursement_ratio> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Hospital_reimbursement_ratio::getHospitalLevel, hospitalLevel)
                .eq(Hospital_reimbursement_ratio::getPersonType, personType)
                .eq(Hospital_reimbursement_ratio::getStaus, "启用")
                .le(Hospital_reimbursement_ratio::getCostMin, totalCost)
                .ge(Hospital_reimbursement_ratio::getCostMax, totalCost)
                .orderByDesc(Hospital_reimbursement_ratio::getUpdateTime)
                .last("LIMIT 1");

        Hospital_reimbursement_ratio ratio = hospitalReimbursementRatioService.getOne(queryWrapper);

        if (ratio == null || ratio.getReimbursementRatio() == null) {
            return vo;
        }

        vo.setDeductible(ratio.getCostMin());
        vo.setCeiling(ratio.getCostMax());
        vo.setReimbursementRatio(ratio.getReimbursementRatio()); // 新增赋值
        if (totalCost.compareTo(ratio.getCostMin()) > 0) {
            BigDecimal base = totalCost.subtract(ratio.getCostMin());
            vo.setReimbursementAmount(
                    base.multiply(ratio.getReimbursementRatio())
                            .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP)
            );
        }
        return vo;
    }


    }

